<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblog/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"kuang-yudi.gitee.io","root":"/myblog/","images":"/myblog/images","scheme":"Gemini","version":"8.1.0","exturl":false,"sidebar":{"position":"right","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":null,"activeClass":"gitalk"},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/myblog/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="js闭包">
<meta property="og:type" content="article">
<meta property="og:title" content="闭包">
<meta property="og:url" content="http://kuang-yudi.gitee.io/myblog/2021/01/14/%E9%97%AD%E5%8C%85/index.html">
<meta property="og:site_name" content="KY迪的个人博客">
<meta property="og:description" content="js闭包">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://kuang-yudi.gitee.io/myblog/2021/01/14/%E9%97%AD%E5%8C%85/闭包.jpg">
<meta property="article:published_time" content="2021-01-14T03:15:13.000Z">
<meta property="article:modified_time" content="2021-01-14T10:44:56.553Z">
<meta property="article:author" content="匡宇迪">
<meta property="article:tag" content="js">
<meta property="article:tag" content="闭包">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://kuang-yudi.gitee.io/myblog/2021/01/14/%E9%97%AD%E5%8C%85/闭包.jpg">


<link rel="canonical" href="http://kuang-yudi.gitee.io/myblog/2021/01/14/%E9%97%AD%E5%8C%85/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>闭包 | KY迪的个人博客</title>
  



  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/myblog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">KY迪的个人博客</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">个人技术博客</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/myblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-tags"><a href="/myblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
        <li class="menu-item menu-item-categories"><a href="/myblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-archives"><a href="/myblog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%A6%82%E5%BF%B5"><span class="nav-number">1.</span> <span class="nav-text">概念</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%89%B9%E7%82%B9"><span class="nav-number">2.</span> <span class="nav-text">特点</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BD%9C%E7%94%A8"><span class="nav-number">3.</span> <span class="nav-text">作用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-number">4.</span> <span class="nav-text">应用场景</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9E%E6%94%B6%E6%9C%BA%E5%88%B6"><span class="nav-number">5.</span> <span class="nav-text">回收机制</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E5%9B%9E%E6%94%B6"><span class="nav-number">5.1.</span> <span class="nav-text">函数回收</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%BC%BA%E7%82%B9"><span class="nav-number">6.</span> <span class="nav-text">缺点</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AE%9E%E4%BE%8B"><span class="nav-number">7.</span> <span class="nav-text">实例</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A0%B8%E5%BF%83"><span class="nav-number">7.1.</span> <span class="nav-text">核心</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E2%80%94%E2%80%94-%E6%99%AE%E9%80%9A%E9%97%AD%E5%8C%85"><span class="nav-number">7.2.</span> <span class="nav-text">1 —— 普通闭包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E2%80%94%E2%80%94-%E5%A4%96%E9%83%A8%E5%87%BD%E6%95%B0%E6%AF%8F%E6%AC%A1%E6%89%A7%E8%A1%8C%E9%83%BD%E5%88%9B%E5%BB%BA%E4%BA%86%E6%96%B0%E7%9A%84%E5%86%85%E5%AD%98%E5%9C%B0%E5%9D%80%EF%BC%8C%E5%88%99%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F%E4%B9%9F%E4%BC%9A%E9%87%8D%E6%96%B0%E5%88%9B%E5%BB%BA"><span class="nav-number">7.3.</span> <span class="nav-text">2 —— 外部函数每次执行都创建了新的内存地址，则局部变量也会重新创建</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E2%80%94%E2%80%94-%E6%94%B9%E5%8F%98%E7%9A%84%E6%98%AF%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%EF%BC%8C%E4%B8%A4%E6%AC%A1%E5%88%9B%E5%BB%BA%E5%A4%96%E9%83%A8%E5%87%BD%E6%95%B0%E8%99%BD%E7%84%B6%E5%86%85%E5%AD%98%E4%B8%8D%E5%90%8C%EF%BC%8C%E4%BD%86%E6%89%BE%E7%9A%84%E5%85%A8%E5%B1%80%E5%8F%98%E9%87%8F%E5%B7%B2%E7%BB%8F%E8%A2%AB%E6%94%B9%E5%8F%98%E3%80%82"><span class="nav-number">7.4.</span> <span class="nav-text">3 —— 改变的是全局变量，两次创建外部函数虽然内存不同，但找的全局变量已经被改变。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E2%80%94%E2%80%94-%E7%B1%BB%E4%BC%BC%E5%AE%9E%E4%BE%8B-2%EF%BC%8C%E5%A4%96%E9%83%A8%E5%87%BD%E6%95%B0%E9%87%8D%E6%96%B0%E8%B0%83%E7%94%A8%E5%88%9B%E5%BB%BA%E6%96%B0%E7%9A%84%E5%86%85%E5%AD%98%E7%A9%BA%E9%97%B4"><span class="nav-number">7.5.</span> <span class="nav-text">4 —— 类似实例 2，外部函数重新调用创建新的内存空间</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E2%80%94%E2%80%94-%E9%87%8D%E6%96%B0%E8%B0%83%E7%94%A8%E5%A4%96%E9%83%A8%E5%87%BD%E6%95%B0%EF%BC%8C%E6%AF%8F%E6%AC%A1%E8%B0%83%E7%94%A8%E7%9A%84%E5%A4%96%E9%83%A8%E5%87%BD%E6%95%B0%E9%83%BD%E6%98%AF%E4%B8%80%E4%B8%AA%E7%8B%AC%E7%AB%8B%E7%A9%BA%E9%97%B4"><span class="nav-number">7.6.</span> <span class="nav-text">5 —— 重新调用外部函数，每次调用的外部函数都是一个独立空间</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-%E2%80%94%E2%80%94-%E7%AB%8B%E5%8D%B3%E6%89%A7%E8%A1%8C%E5%87%BD%E6%95%B0%E4%B8%AD%E5%88%9B%E5%BB%BA%E4%BA%86%E4%B8%80%E4%B8%AA%E4%BD%9C%E7%94%A8%E5%9F%9F%EF%BC%8C%E5%B1%80%E9%83%A8%E5%8F%98%E9%87%8F%E7%9A%84%E5%80%BC%E8%A2%AB%E6%94%B9%E5%8F%98"><span class="nav-number">7.7.</span> <span class="nav-text">6 —— 立即执行函数中创建了一个作用域，局部变量的值被改变</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-%E2%80%94%E2%80%94-%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="nav-number">7.8.</span> <span class="nav-text">7 —— 链式调用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-%E2%80%94%E2%80%94-%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0%E4%B8%AD%E9%97%AD%E5%8C%85%E7%9A%84%E5%86%99%E6%B3%95"><span class="nav-number">7.9.</span> <span class="nav-text">8 —— 事件处理函数中闭包的写法</span></a></li></ol></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="匡宇迪"
      src="https://static.pptstore.net/picture/19/19/e1feb44f42cdf7e1202b_s.jpg">
  <p class="site-author-name" itemprop="name">匡宇迪</p>
  <div class="site-description" itemprop="description">用于记录学习web前端</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblog/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblog/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/myblog/tags/">
          
        <span class="site-state-item-count">87</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/tonykyd/tonykyd.github.io" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tonykyd&#x2F;tonykyd.github.io" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1303665509@qq.com" title="E-Mail → mailto:1303665509@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://kuang-yudi.gitee.io/myblog/2021/01/14/%E9%97%AD%E5%8C%85/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://static.pptstore.net/picture/19/19/e1feb44f42cdf7e1202b_s.jpg">
      <meta itemprop="name" content="匡宇迪">
      <meta itemprop="description" content="用于记录学习web前端">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="KY迪的个人博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          闭包
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-01-14 11:15:13 / 修改时间：18:44:56" itemprop="dateCreated datePublished" datetime="2021-01-14T11:15:13+08:00">2021-01-14</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/myblog/categories/%E9%9D%A2%E8%AF%95%E9%A2%98/" itemprop="url" rel="index"><span itemprop="name">面试题</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

            <div class="post-description">js闭包</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h1><p>闭包函数：声明在一个函数中的函数，叫做闭包函数。</p>
<p>闭包：内部函数总是可以访问其所在的外部函数中声明的参数和变量，即使在其外部函数被返回（寿命终结）了之后。</p>
<h1 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h1><p>让外部访问函数内部变量成为可能；</p>
<p>局部变量会常驻在内存中；</p>
<p>可以避免使用全局变量，防止全局变量污染；</p>
<p>会造成内存泄漏（有一块内存空间被长期占用，而不被释放）</p>
<h1 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h1><p>在函数 a 执行完并返回后，闭包使得 JavaScript 的垃圾回收机制不会收回 a 所占用的资源，因为 a 的内部函数 b 的执行需要依赖 a 中的变量，闭包需要循序渐进的过程。</p>
<h1 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景"></a>应用场景</h1><ol>
<li>保护函数内的变量安全。函数 a 中只有函数 b 才能访问，而无法通过其他途径访问到，因此保护了函数 a 中变量的安全性。</li>
<li>在内存中维持一个变量</li>
</ol>
<h1 id="回收机制"><a href="#回收机制" class="headerlink" title="回收机制"></a>回收机制</h1><p>在 JavaScript 中，如果一个对象不再被引用，那么这个对象就会被 GC 回收。如果俩个对象互相引用，而不再被第 3 者所引用，那么这俩个互相引用的对象也会被回收。因为函数 a 中的变量被函数 b 引用，b 又被 a 外的 c 引用(调用)，这就是为什么函数 a 执行后不会被回收的原因。例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">var num &#x3D; 6;</span><br><span class="line">function outer() &#123;</span><br><span class="line">	var num &#x3D; 1;</span><br><span class="line">	function inner() &#123;</span><br><span class="line">		var n &#x3D; 2;</span><br><span class="line">		alert(n + num);</span><br><span class="line">	&#125;</span><br><span class="line">	return inner</span><br><span class="line">&#125;</span><br><span class="line">const test &#x3D; outer(); &#x2F;&#x2F; 相当于test&#x3D;inner</span><br><span class="line">test(); &#x2F;&#x2F; 即inner()</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="函数回收"><a href="#函数回收" class="headerlink" title="函数回收"></a>函数回收</h2><p>调用函数的时候，系统会分配对应的空间给这个函数使用（空间大小一般情况由这个函数里声明的变量和形参决定），当函数使用完毕以后，这个内存空间要释放，还给系统。</p>
<p><strong>注意：在函数内部声明的变量和形参是属于当前函数的内存空间的。</strong></p>
<h1 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h1><p>滥用闭包会造成内存泄露，因为闭包中引用到的包裹函数中定义的变量都永远不会被释放，所以我们应该在必要的时候，及时释放这个闭包函数。</p>
<h1 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h1><h2 id="核心"><a href="#核心" class="headerlink" title="核心"></a>核心</h2><ol>
<li>闭包找到的是同一地址中父级函数中对应变量最终的值</li>
<li>在外部函数没有重新执行的情况下，闭包函数内访问的是局部变量最终的值</li>
<li>每次调用外部函数都是创建了新的内存</li>
<li>闭包函数中未声明变量的查找是通过作用域链向外查找</li>
</ol>
<p>如图：</p>
<img src="闭包.jpg"/>

<h2 id="1-——-普通闭包"><a href="#1-——-普通闭包" class="headerlink" title="1 —— 普通闭包"></a>1 —— 普通闭包</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function funA()&#123;</span><br><span class="line">  var a &#x3D; 10;  &#x2F;&#x2F; funA的活动对象之中;</span><br><span class="line">  return function()&#123;   &#x2F;&#x2F;匿名函数的活动对象;</span><br><span class="line">        alert(a);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">var b &#x3D; funA();</span><br><span class="line">b();  &#x2F;&#x2F;10</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="2-——-外部函数每次执行都创建了新的内存地址，则局部变量也会重新创建"><a href="#2-——-外部函数每次执行都创建了新的内存地址，则局部变量也会重新创建" class="headerlink" title="2 —— 外部函数每次执行都创建了新的内存地址，则局部变量也会重新创建"></a>2 —— 外部函数每次执行都创建了新的内存地址，则局部变量也会重新创建</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">function outerFn()&#123;</span><br><span class="line">  var i &#x3D; 0;</span><br><span class="line">  function innerFn()&#123;</span><br><span class="line">      i++;</span><br><span class="line">      console.log(i);</span><br><span class="line">  &#125;</span><br><span class="line">  return innerFn;</span><br><span class="line">&#125;</span><br><span class="line">var inner &#x3D; outerFn();  &#x2F;&#x2F;每次外部函数执行的时候,都会开辟一块内存空间,外部函数的地址不同，都会重新创建一个新的地址</span><br><span class="line">inner();</span><br><span class="line">inner();</span><br><span class="line">inner();</span><br><span class="line">var inner2 &#x3D; outerFn(); &#x2F;&#x2F; 创建了新的内存空间</span><br><span class="line">inner2();</span><br><span class="line">inner2();</span><br><span class="line">inner2();   &#x2F;&#x2F;1 2 3 1 2 3</span><br></pre></td></tr></table></figure>

<h2 id="3-——-改变的是全局变量，两次创建外部函数虽然内存不同，但找的全局变量已经被改变。"><a href="#3-——-改变的是全局变量，两次创建外部函数虽然内存不同，但找的全局变量已经被改变。" class="headerlink" title="3 —— 改变的是全局变量，两次创建外部函数虽然内存不同，但找的全局变量已经被改变。"></a>3 —— 改变的是全局变量，两次创建外部函数虽然内存不同，但找的全局变量已经被改变。</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">var i &#x3D; 0;</span><br><span class="line">function outerFn()&#123;</span><br><span class="line">  function innnerFn()&#123;</span><br><span class="line">       i++;</span><br><span class="line">       console.log(i);</span><br><span class="line">  &#125;</span><br><span class="line">  return innnerFn;</span><br><span class="line">&#125;</span><br><span class="line">var inner1 &#x3D; outerFn();</span><br><span class="line">var inner2 &#x3D; outerFn();</span><br><span class="line">inner1();</span><br><span class="line">inner2();</span><br><span class="line">inner1();</span><br><span class="line">inner2();     &#x2F;&#x2F;1 2 3 4</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="4-——-类似实例-2，外部函数重新调用创建新的内存空间"><a href="#4-——-类似实例-2，外部函数重新调用创建新的内存空间" class="headerlink" title="4 —— 类似实例 2，外部函数重新调用创建新的内存空间"></a>4 —— 类似实例 2，外部函数重新调用创建新的内存空间</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function fn()&#123;</span><br><span class="line">	var a &#x3D; 3;</span><br><span class="line">	return function()&#123;</span><br><span class="line">		return  ++a;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">alert(fn()());  &#x2F;&#x2F;4</span><br><span class="line">alert(fn()());  &#x2F;&#x2F;4</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="5-——-重新调用外部函数，每次调用的外部函数都是一个独立空间"><a href="#5-——-重新调用外部函数，每次调用的外部函数都是一个独立空间" class="headerlink" title="5 —— 重新调用外部函数，每次调用的外部函数都是一个独立空间"></a>5 —— 重新调用外部函数，每次调用的外部函数都是一个独立空间</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">function outerFn()&#123;</span><br><span class="line">  var i &#x3D; 0;</span><br><span class="line">  function innnerFn()&#123;</span><br><span class="line">      i++;</span><br><span class="line">      console.log(i);</span><br><span class="line">  &#125;</span><br><span class="line">  return innnerFn;</span><br><span class="line">&#125;</span><br><span class="line">var inner1 &#x3D; outerFn();</span><br><span class="line">var inner2 &#x3D; outerFn();</span><br><span class="line">inner1();</span><br><span class="line">inner2();</span><br><span class="line">inner1();</span><br><span class="line">inner2();    &#x2F;&#x2F;1 1 2 2</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="6-——-立即执行函数中创建了一个作用域，局部变量的值被改变"><a href="#6-——-立即执行函数中创建了一个作用域，局部变量的值被改变" class="headerlink" title="6 —— 立即执行函数中创建了一个作用域，局部变量的值被改变"></a>6 —— 立即执行函数中创建了一个作用域，局部变量的值被改变</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">(function() &#123;</span><br><span class="line">  var m &#x3D; 0;</span><br><span class="line">  function getM() &#123; return m; &#125;</span><br><span class="line">  function seta(val) &#123; m &#x3D; val; &#125;</span><br><span class="line">  window.g &#x3D; getM;</span><br><span class="line">  window.f &#x3D; seta;</span><br><span class="line">&#125;)();</span><br><span class="line">f(100);</span><br><span class="line">console.info(g());   &#x2F;&#x2F;100  闭包找到的是同一地址中父级函数中对应变量最终的值</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="7-——-链式调用"><a href="#7-——-链式调用" class="headerlink" title="7 —— 链式调用"></a>7 —— 链式调用</h2><p>add(1)(2)(3)相当于 tmp(2)(3),tmp(2)改变 sum 的值为 3，tmp(3)改变 sum 值为 6</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">var add &#x3D; function(x) &#123;</span><br><span class="line">  var sum &#x3D; 1;</span><br><span class="line">  var tmp &#x3D; function(x) &#123;</span><br><span class="line">      sum &#x3D; sum + x;</span><br><span class="line">      return tmp;</span><br><span class="line">  &#125;</span><br><span class="line">  &#x2F;&#x2F; 函数toString方法设置输出此函数时显示的内容</span><br><span class="line">  tmp.toString &#x3D; function() &#123;</span><br><span class="line">      return sum;</span><br><span class="line">  &#125;</span><br><span class="line">  return tmp;</span><br><span class="line">&#125;</span><br><span class="line">alert(add(1)(2)(3));</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="8-——-事件处理函数中闭包的写法"><a href="#8-——-事件处理函数中闭包的写法" class="headerlink" title="8 —— 事件处理函数中闭包的写法"></a>8 —— 事件处理函数中闭包的写法</h2><p>通过创建立即执行函数，每次循环都有自己的作用域（立即执行函数创建独立的作用域）</p>
<p>事件函数属于异步任务，触发前循环已经完成，如果没有独立的作用域，那么 var 声明的 i 属于全局变量,通过立即执行函数让每次循环创建了独立的作用域，储存对应的变量值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var lis &#x3D; document.getElementsByTagName(&quot;li&quot;);</span><br><span class="line">for(var i&#x3D;0;i&lt;lis.length;i++)&#123;</span><br><span class="line">  (function(i)&#123;</span><br><span class="line">      lis[i].onclick &#x3D; function()&#123;</span><br><span class="line">           console.log(i);</span><br><span class="line">      &#125;;</span><br><span class="line">  &#125;)(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="followme">
  <span>欢迎关注我的其它发布渠道</span>

  <div class="social-list">

      <div class="social-item">
        <a target="_blank" class="social-link" href="/myblog/images/wechat_channel.jpg">
          <span class="icon">
            <i class="fab fa-weixin"></i>
          </span>

          <span class="label">WeChat</span>
        </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/myblog/tags/js/" rel="tag"># js</a>
              <a href="/myblog/tags/%E9%97%AD%E5%8C%85/" rel="tag"># 闭包</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/myblog/2021/01/13/js%E4%B8%AD%E7%9A%84%E7%BB%A7%E6%89%BF%E6%96%B9%E6%B3%95/" rel="prev" title="js中的继承方法">
                  <i class="fa fa-chevron-left"></i> js中的继承方法
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/myblog/2021/01/14/%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D/" rel="next" title="数组去重">
                  数组去重 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments" id="gitalk-container"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">匡宇迪</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/myblog/js/utils.js"></script><script src="/myblog/js/motion.js"></script><script src="/myblog/js/next-boot.js"></script>

  
<script src="/myblog/js/local-search.js"></script>






  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>






<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1.7.0/dist/gitalk.css">

<script>
NexT.utils.loadComments('#gitalk-container', () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1.7.0/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '1926f8a1c453a1121d8d',
      clientSecret: '426722f9eef7599f8ebb3220379e704ea007a5f2',
      repo        : '',
      owner       : '',
      admin       : [''],
      id          : 'cdd8d9b83305632b0ae6e9327d4e6d58',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>

</body>
</html>
